<?php

namespace App\Http\Controllers;

use App\Model\Book;
use App\Model\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    //首页渲染
    public function index(){
        $userid = \Cache::get($_COOKIE['userid']);
        $user = Student::where('userid',$userid)->first();
        return view('index',['user' => $user,'isQuery' => 0]);
    }

    //书籍查询
    public function getBooks(Request $request){
        $userid = \Cache::get($_COOKIE['userid']);
        $user = Student::where('userid',$userid)->first();
        $select = $request->input('query');
        $data = trim($request->input('data'));
        switch ($select){
            case 'bookid':
                $books = Book::where('bookid',$data)->get();
                break;
            case 'name':
                $books = Book::where('name',$data)->get();
                break;
            case 'author':
                $books = Book::where('author',$data)->get();
                break;
            case 'publisher':
                $books = Book::where('publisher',$data)->get();
                break;
            case 'type':
                $books = Book::where('type',$data)->get();
                break;
            case 'all':
                $books = Book::all();
                break;
        }
        return view('index',['user' => $user,'books' => $books,'isQuery' => 1]);
    }

    //借书
    public function lendBook($id){
        $userid = \Cache::get($_COOKIE['userid']);
        $user = Student::where('userid',$userid)->first();
        $userBookExist = $user->books()->find($id);
        if ($userBookExist){
            die('您已借阅过此图书，不能重复借阅！');
        }
        $user->books()->attach($id,['return_date' => date('Y-m-d',time()+2595600)]);
        die('借书成功！');
    }

}
